/* eslint-disable react-refresh/only-export-components */
import { useLoaderData, useNavigate } from 'react-router-dom'
import { getSwiperApi } from '../../../api/info'
import {
  ResultPage,
  Switch,
  Button,
  Popup,
  CalendarPickerView
} from 'antd-mobile'
import MySwiper from '../../../components/swiper'
import { LoopOutline } from 'antd-mobile-icons'
import { useSelector, useDispatch } from 'react-redux'
import {
  exchangeCity,
  setIsSpeed,
  setDate
} from '../../../store/slice/ticketSlice'
import { useState, useMemo } from 'react'
import { dtFormat } from '../../../utils'
import styles from './css/home.module.css'

function Home() {
  // 使用 useLoaderData() hook 获取 loader 函数 return 给组件的数据
  // 3. 在组件中，通过 useLoaderData() 这个 Hook，获取到轮播图的数据
  const loaderData = useLoaderData()
  const start = useSelector((store) => store.ticket.start)
  const end = useSelector((store) => store.ticket.end)
  const date = useSelector((store) => store.ticket.date)
  const isSpeed = useSelector((store) => store.ticket.isSpeed)
  const dispatch = useDispatch()
  const nav = useNavigate()

  const [visible5, setVisible5] = useState(false)

  const dtObj = useMemo(() => dtFormat(date), [date])

  // 4. 在 DOM 区域进行轮播图的循环渲染
  return (
    <div className={styles.box}>
      <ResultPage
        status=""
        title="火车票预订"
        description="便捷购票，服务您的每一次出行"
      >
        <ResultPage.Card style={{ padding: 12 }}>
          <div className={styles.row}>
            {/* 出发地 */}
            <span
              className={styles.start}
              onClick={() => nav('/city/start')}
            >
              {start}
            </span>
            {/* 交换城市的按钮 */}
            <LoopOutline
              fontSize={26}
              onClick={() => dispatch(exchangeCity())}
            />
            {/* 目的地 */}
            <span
              className={styles.end}
              onClick={() => nav('/city/end')}
            >
              {end}
            </span>
          </div>
          {/* 选择乘车日期 */}
          <div
            className={styles.row}
            onClick={() => setVisible5(true)}
          >
            <div>
              <span className={styles.date}>{date}</span>
              <span className={styles.week}>
                {dtObj.week}
                {dtObj.info ? ` (${dtObj.info})` : ''}
              </span>
            </div>
          </div>
          <div className={styles.row}>
            <span className={styles.isSpeed}>只看高铁/动车</span>
            <Switch
              checked={isSpeed}
              onChange={(val) => {
                // 把形参中的 val,调用全局方法，存到 Store
                dispatch(setIsSpeed(val))
              }}
            />
          </div>
          <div className={styles.row}>
            <Button
              block
              color="warning"
              shape="rounded"
              onClick={() =>
                nav(
                  `/query?start=${start}&end=${end}&date=${date}&isSpeed=${isSpeed}`
                )
              }
            >
              搜索
            </Button>
          </div>
        </ResultPage.Card>

        {/* 使用自定义的轮播图组件 */}
        <MySwiper list={loaderData.swiperList} />
      </ResultPage>

      <Popup
        visible={visible5}
        onMaskClick={() => {
          setVisible5(false)
        }}
        bodyStyle={{
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
          minHeight: '40vh'
        }}
      >
        {/* 日历组件 */}
        <CalendarPickerView
          value={date}
          min={Date.now()}
          max={Date.now() + 14 * 24 * 60 * 60 * 1000}
          onChange={(val) => {
            if (val) {
              dispatch(setDate(val.toString()))
            }
            setVisible5(false)
          }}
          renderTop={false}
          renderBottom={(dt) => dtFormat(dt).info}
        />
      </Popup>
    </div>
  )
}

// 导出函数式组件
export default Home

// 导出这个函数式组件需要用到的 loader 函数
export const loader = async () => {
  // 1. 调用接口，请求轮播图数据
  const { data: res } = await getSwiperApi()
  // 2. 把请求回来的轮播图数据，挂载到 return 的这个对象中
  return { swiperList: res }
}
